package com.example.internalcommon.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.internalcommon.dto.TokenResult;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author lyra
 * @Date 2023/4/5 16:11
 **/

public class JwtUtils {
    // 盐sign
    private static final String SIGN = "CPFmsb!@#$$";

    private static final String JWT_KEY_PHONE = "Phone";

    // 假定乘客是1 , 司机是2
    private static final String JWT_KEY_IDENTITY = "identity";

    // token的类型
    private static final String JWT_TOKEN_TYPE = "tokenType";

    private static final String JWT_TOKEN_TIME = "tokenTime";

    // 5.生成token
    public static String generatorToken(String phone,String identity,String tokenType) {
        HashMap<String, String> map = new HashMap<>();
        // map.put(JWT_KEY, passengerPhone);
        map.put(JWT_KEY_PHONE , phone);
        map.put(JWT_KEY_IDENTITY , identity);
        map.put(JWT_TOKEN_TYPE, tokenType);

        // token过期时间
        Calendar calendar = Calendar.getInstance();

        // 在token生成时加入当前时间,确保token的值不是同一个
        calendar.add(Calendar.DATE, 1);
        map.put(JWT_TOKEN_TIME, Calendar.getInstance().getTime().toString());
        JWTCreator.Builder builder = JWT.create();

        // 整合map
        map.forEach(
                (k,v)->{
                    builder.withClaim(k, v);
                }
        );

        // 整合过期时间 ( 不设置过期时间 )
        // builder.withExpiresAt(date);
        // 生成token字符串
        String sign = builder.sign(Algorithm.HMAC256(SIGN));
        return sign;
    }


    // 6.解析token 并 返回解析后的结果
    public static TokenResult parseToken(String token){
        // (1)解析token
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        // (2)把token中的phone解析出来
        String phone = verify.getClaim(JWT_KEY_PHONE).asString();
        // (3)把token中的IDENTITY解析出来
        String identity = verify.getClaim(JWT_KEY_IDENTITY).asString();
        TokenResult tokenResult = new TokenResult();
        tokenResult.setPhone(phone);
        tokenResult.setIdentity(identity);
        return tokenResult;
    }

    /**
     * 校验token,主要校验token是否异常
     * @param token
     * @return
     */
    public static TokenResult checkToken(String token){
        TokenResult tokenResult = null;
        try {
            tokenResult = JwtUtils.parseToken(token);              // 解析token
        } catch (Exception e){

        }/* catch (SignatureVerificationException e) { // 签名异常
            resultString = "token sign error";
            result = false;
        }catch (TokenExpiredException e){            // token过期
            resultString = "token time out";
            result = true;
        }catch (AlgorithmMismatchException e){       // 算法不匹配异常
            resultString = "token AlgorithmMismatchException";
            result = false;
        }catch (Exception e){                        // 其他异常
            resultString = "token invalid";
            result = false;
        }*/
        return tokenResult;
    }


    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        //生成token
        String s = generatorToken("13910733521","1","");
        System.out.println("生成的token = " + s);
        //解析token
        TokenResult tokenResult = parseToken(s);
        System.out.println("解析token后的值" + parseToken(s));
        System.out.println(tokenResult.getPhone());
        System.out.println(tokenResult.getIdentity());
    }


}
